<template>
  <div class="user-form">
    <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          action="/api/user/avatar"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar">
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userForm.username" disabled></el-input>
      </el-form-item>
      
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="userForm.nickname"></el-input>
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userForm.email"></el-input>
      </el-form-item>
      
      <el-form-item label="手机" prop="phone">
        <el-input v-model="userForm.phone">
          <template #append>
            <el-button @click="showBindPhoneDialog">{{ userForm.phone ? '修改' : '绑定' }}</el-button>
          </template>
        </el-input>
      </el-form-item>
      
      <el-form-item label="学校" prop="school">
        <el-input v-model="userForm.school"></el-input>
      </el-form-item>
      
      <el-form-item label="年级" prop="grade">
        <el-select v-model="userForm.grade" placeholder="请选择年级" style="width: 100%">
          <el-option label="初一" value="初一"></el-option>
          <el-option label="初二" value="初二"></el-option>
          <el-option label="初三" value="初三"></el-option>
          <el-option label="高一" value="高一"></el-option>
          <el-option label="高二" value="高二"></el-option>
          <el-option label="高三" value="高三"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="个人简介" prop="bio">
        <el-input type="textarea" v-model="userForm.bio" :rows="4"></el-input>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="updateUserInfo">保存修改</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    
    <el-divider content-position="center">安全设置</el-divider>
    
    <div class="security-settings">
      <el-button type="primary" @click="showChangePasswordDialog">修改密码</el-button>
      <el-button type="danger" @click="showDeleteAccountDialog">注销账号</el-button>
    </div>
    
    <!-- 修改密码对话框 -->
    <el-dialog v-model="changePasswordDialogVisible" title="修改密码" width="400px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input v-model="passwordForm.currentPassword" type="password" show-password></el-input>
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="changePasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="changePassword">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 绑定手机对话框 -->
    <el-dialog v-model="bindPhoneDialogVisible" title="绑定手机" width="400px">
      <el-form :model="phoneForm" :rules="phoneRules" ref="phoneFormRef" label-width="100px">
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="phoneForm.phone">
            <template #append>
              <el-button 
                @click="sendVerificationCode" 
                :disabled="codeButtonDisabled"
              >{{ codeButtonText }}</el-button>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="验证码" prop="verificationCode">
          <el-input v-model="phoneForm.verificationCode"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bindPhoneDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="bindPhone">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 注销账号对话框 -->
    <el-dialog v-model="deleteAccountDialogVisible" title="注销账号" width="400px">
      <div class="warning-message">
        <el-alert
          title="警告：账号注销后将无法恢复，所有数据将被永久删除！"
          type="warning"
          :closable="false"
          show-icon
        ></el-alert>
      </div>
      
      <el-form :model="deleteAccountForm" :rules="deleteAccountRules" ref="deleteAccountFormRef" label-width="100px">
        <el-form-item label="密码" prop="password">
          <el-input v-model="deleteAccountForm.password" type="password" show-password></el-input>
        </el-form-item>
        
        <el-form-item label="确认注销" prop="confirm">
          <el-checkbox v-model="deleteAccountForm.confirm">我确认要注销我的账号</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteAccountDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteAccount">注销账号</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const router = useRouter();

const props = defineProps({
  userInfo: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['update-user-info']);

// 表单数据
const userForm = reactive({
  username: props.userInfo.username,
  nickname: props.userInfo.nickname,
  email: props.userInfo.email,
  phone: props.userInfo.phone,
  avatar: props.userInfo.avatar,
  school: props.userInfo.school,
  grade: props.userInfo.grade,
  bio: props.userInfo.bio
});

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
});

const phoneForm = reactive({
  phone: '',
  verificationCode: ''
});

const deleteAccountForm = reactive({
  password: '',
  confirm: false
});

// 表单验证规则
const userRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  school: [
    { max: 50, message: '长度不能超过 50 个字符', trigger: 'blur' }
  ],
  bio: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ]
};

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }
  ]
};

const phoneRules = {
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为 6 位', trigger: 'blur' }
  ]
};

const deleteAccountRules = {
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  confirm: [
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请确认注销账号'));
        } else {
          callback();
        }
      }, 
      trigger: 'change' 
    }
  ]
};

// 引用
const userFormRef = ref(null);
const passwordFormRef = ref(null);
const phoneFormRef = ref(null);
const deleteAccountFormRef = ref(null);

// 对话框可见性
const changePasswordDialogVisible = ref(false);
const bindPhoneDialogVisible = ref(false);
const deleteAccountDialogVisible = ref(false);

// 验证码按钮状态
const codeButtonDisabled = ref(false);
const codeButtonText = ref('获取验证码');
let countdownTimer = null;

// 方法：头像上传成功
const handleAvatarSuccess = (response) => {
  userForm.avatar = response.data;
  ElMessage.success('头像上传成功');
};

// 方法：头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

// 方法：更新用户信息
const updateUserInfo = () => {
  userFormRef.value.validate((valid) => {
    if (valid) {
      // 更新用户信息
      emit('update-user-info', { ...userForm });
      ElMessage.success('个人信息已更新');
    } else {
      return false;
    }
  });
};

// 方法：重置表单
const resetForm = () => {
  userFormRef.value.resetFields();
};

// 方法：显示修改密码对话框
const showChangePasswordDialog = () => {
  passwordForm.currentPassword = '';
  passwordForm.newPassword = '';
  passwordForm.confirmPassword = '';
  changePasswordDialogVisible.value = true;
};

// 方法：修改密码
const changePassword = () => {
  passwordFormRef.value.validate((valid) => {
    if (valid) {
      // 这里应该调用API修改密码
      ElMessage.success('密码修改成功');
      changePasswordDialogVisible.value = false;
    } else {
      return false;
    }
  });
};

// 方法：显示绑定手机对话框
const showBindPhoneDialog = () => {
  phoneForm.phone = props.userInfo.phone || '';
  phoneForm.verificationCode = '';
  bindPhoneDialogVisible.value = true;
};

// 方法：发送验证码
const sendVerificationCode = () => {
  phoneFormRef.value.validateField('phone', (valid) => {
    if (!valid) {
      // 开始倒计时
      codeButtonDisabled.value = true;
      let countdown = 60;
      codeButtonText.value = `${countdown}秒后重新获取`;
      
      countdownTimer = setInterval(() => {
        countdown--;
        codeButtonText.value = `${countdown}秒后重新获取`;
        if (countdown <= 0) {
          clearInterval(countdownTimer);
          codeButtonDisabled.value = false;
          codeButtonText.value = '获取验证码';
        }
      }, 1000);
      
      // 这里应该调用API发送验证码
      ElMessage.success('验证码已发送');
    }
  });
};

// 方法：绑定手机
const bindPhone = () => {
  phoneFormRef.value.validate((valid) => {
    if (valid) {
      // 这里应该调用API绑定手机
      userForm.phone = phoneForm.phone;
      ElMessage.success('手机绑定成功');
      bindPhoneDialogVisible.value = false;
    } else {
      return false;
    }
  });
};

// 方法：显示注销账号对话框
const showDeleteAccountDialog = () => {
  deleteAccountForm.password = '';
  deleteAccountForm.confirm = false;
  deleteAccountDialogVisible.value = true;
};

// 方法：注销账号
const deleteAccount = () => {
  deleteAccountFormRef.value.validate((valid) => {
    if (valid) {
      // 这里应该调用API注销账号
      ElMessage.success('账号已注销');
      deleteAccountDialogVisible.value = false;
      // 注销后应该跳转到登录页
      router.push('/login');
    } else {
      return false;
    }
  });
};
</script>

<style scoped>
/* 用户表单样式 */
.user-form {
  max-width: 600px;
  margin: 0 auto;
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.security-settings {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

/* 对话框样式 */
.warning-message {
  margin-bottom: 20px;
}
</style>